<template>
    <div class="bground">
        <el-container style="height: auto;">
            <el-header style="background-color: #24b1f5;height:80px;text-align: center">
                <!--                    <div style="align-items: center;height:100%">-->
                <!-- 返回 -->
                <el-page-header style="height:80px; line-height: 30px; padding-top: 20px; ">
                    <template #title>
                        <div>
                            <el-link @click="toHome" style="font-size: 25px;text-align: center; font-weight: bolder; color: #f5f5f5">返回</el-link>
                        </div>
                    </template>
                    <template #content>
                        <span class="custom-span" v-for="(item) in merchant" style="align-items: center; line-height: 30px; font-size: 30px; margin: auto 16px; font-weight: bolder; color: #fefdfc;">
                            欢迎来到{{ item.shopName }}
                            <img v-if="showSc" style="height:30px;width:30px;justify-content: center; margin-left: 10px;" @click="addSc" src="../../public/img/resources/sc0.png" />
                            <img v-if="!showSc" style="height:30px;width:30px;justify-content: center; margin-left: 10px;" @click="deleteSc" src="../../public/img/resources/sc1.png" />
                        </span>
                    </template>
                </el-page-header>
            </el-header>
            <el-container>
                <div style="width:200px; height: 100%">
                    <el-aside width="200px" style="overflow: hidden">
                        <el-row class="tac" style="width:300px">
                            <el-col :span="12">
                                <el-menu default-active="2" class="el-menu-vertical-demo" style="background-color: rgb(176, 224, 230, 0.4)" @open="handleOpen" @close="handleClose">
                                    <el-sub-menu index="2">
                                        <template #title>
                                            <el-icon>
                                                <Bowl />
                                            </el-icon>
                                            <span style="font-size: 20px;font-weight: 300;">本店菜系</span>
                                        </template>
                                        <el-menu-item-group class="menu-item-group" v-for="item in category" @click="btnToMenu(item.id)">
                                            <template #title>
                                                <span class="title-style">{{ item.name }}</span>
                                            </template>
                                        </el-menu-item-group>
                                    </el-sub-menu>
                                    <el-menu-item index="1" @click="toIndex">
                                        <el-icon>
                                            <HomeFilled />
                                        </el-icon>
                                        <span style="font-size: 20px;font-weight: 300;">主&emsp;&emsp;页</span>
                                    </el-menu-item>
                                    <el-menu-item index="3" @click="openHot">
                                        <el-icon><icon-menu /></el-icon>
                                        <span style="font-size: 20px;font-weight: 300;">推荐菜品</span>
                                    </el-menu-item>
                                    <el-menu-item index="4" @click="openCart">
                                        <el-icon>
                                            <ShoppingCart />
                                        </el-icon>
                                        <span style="font-size: 20px;font-weight: 300;">已选菜品</span>
                                        <el-drawer v-model="cart" direction="rtl" size="35%">
                                            <template #title>
                                                <div class="custom-title">
                                                    已选菜品全在这里啦
                                                </div>
                                            </template>
                                            <el-button type="primary" round @click="toZero">清空</el-button>
                                            <el-button type="primary" round @click="deleteSelect">删除已选</el-button>
                                            <el-table :data="Foods" @selection-change="handleSelectionChange" style="width: 100% ; height:70%">
                                                <el-table-column type="selection" width="30px" />
                                                <!--                                                    <el-table-column prop="id" label="编号" width="60px"  />-->
                                                <el-table-column prop="image" label="图片" width="70px">
                                                    <template #default="scope">
                                                        <el-avatar shape="square" :size="60" :src="scope.row.image" class="avatar" />
                                                    </template>
                                                </el-table-column>
                                                <el-table-column prop="name" label="名称" width="80px" />
                                                <el-table-column prop="price" label="单价" width="80px" />
                                                <el-table-column prop="number" label="操作" width="280px">
                                                    <template #default="scope">
                                                        <el-input-number v-model="scope.row.number" :min="1" size="small" @change="changeOrder(scope.row.number, scope.row.cartId)" />
                                                        <el-button type="warning" :icon="Star" circle style="height:40px;width:40px;margin: 0 10px;" @click="toLike(scope.row.id)" />
                                                        <el-button type="danger" :icon="Delete" circle style="height:40px;width:40px;margin: 0 10px;" @click="deleteIt(scope.row.id)" />
                                                    </template>
                                                </el-table-column>
                                            </el-table>

                                            <div style="display: flex; align-items: center;">
                                                <img src="../../public/img/resources/money.png" style=" height: 20px;width:20px">
                                                <span style="margin-left: 5px;">已选{{ amountSelect }}元</span>
                                                &ensp;&ensp;&ensp;
                                                <img src="../../public/img/resources/money.png" style=" height: 20px;width:20px">
                                                <span style="margin-left: 5px;">共计{{ amount }}元</span>
                                            </div>
                                            <el-button type="primary" round :disabled="checkOrderFee" @click="btnSubmit">{{ buttonText }}</el-button>
                                            <el-dialog v-model="outerVisible" title="订单确认" style="width: 550px">
                                                <el-table :data="multipleSelection" style="width: 100%">
                                                    <el-table-column prop="image" label="图片" width="120">
                                                        <template #default="scope">
                                                            <el-avatar shape="square" :size="50" :src="scope.row.image" class="avatar" />
                                                        </template>
                                                    </el-table-column>
                                                    <el-table-column prop="name" label="名称" width="120" />
                                                    <el-table-column prop="price" label="单价" width="120" />
                                                    <el-table-column prop="number" label="数量" width="120" />
                                                </el-table>
                                                地址选择：
                                                <el-select v-model="addressNow" class="m-2" placeholder="请选择配送地址" size="large" style="width: 400px">
                                                    <el-option style="height: 120px" v-for="item in address" :value="item.id" :label="item.name" @click="changeAddress(item.id,item.index)">
                                                        <el-descriptions class="margin-top" :column="2" border>
                                                            <el-descriptions-item>
                                                                <template #label>
                                                                    <div class="cell-item">
                                                                        <el-icon>
                                                                            <user />
                                                                        </el-icon>
                                                                    </div>
                                                                </template>
                                                                {{ item.consignee }}
                                                            </el-descriptions-item>
                                                            <el-descriptions-item>
                                                                <template #label>
                                                                    <div class="cell-item">
                                                                        <el-icon>
                                                                            <iphone />
                                                                        </el-icon>
                                                                    </div>
                                                                </template>
                                                                {{ item.phone }}
                                                            </el-descriptions-item>
                                                            <el-descriptions-item>
                                                                <template #label>
                                                                    <div class="cell-item">
                                                                        <el-icon>
                                                                            <office-building />
                                                                        </el-icon>
                                                                    </div>
                                                                </template>
                                                                {{ item.provinceName }}{{ item.cityName }}{{ item.districtName }}{{ item.detail }}
                                                            </el-descriptions-item>
                                                            <div class="cell-item">
                                                                <el-icon>
                                                                    <edit />
                                                                </el-icon>
                                                            </div>
                                                        </el-descriptions>
                                                    </el-option>
                                                </el-select>
                                                <br>
                                                客户备注：
                                                <el-input v-model="note" autosize maxlength="30" style="width: 400px;display: inline-block;" type="textarea" placeholder="有什么需要请在这里填写" />
                                                <br>
                                                支付方式：
                                                <el-radio-group v-model="payMethod">
                                                    <el-radio :label="0" :key="0" :value="0" class="radio-item">
                                                        <div class="radio-content">
                                                            <el-avatar shape="square" :size="20" src="../../public/img/zfb.png" class="avatar" />
                                                            <span class="radio-text">支付宝</span>
                                                        </div>
                                                    </el-radio>
                                                    <el-radio :label="1" :key="1" :value="1" class="radio-item">
                                                        <div class="radio-content">
                                                            <el-avatar shape="square" :size="20" src="../../public/img/wx.png" class="avatar" />
                                                            <span class="radio-text">微信</span>
                                                        </div>
                                                    </el-radio>
                                                    <el-radio :label="2" :key="2" :value="2" class="radio-item">
                                                        <div class="radio-content">
                                                            <el-avatar shape="square" :size="20" src="../../public/img/yhk.png" class="avatar" />
                                                            <span class="radio-text">银行卡</span>
                                                        </div>
                                                    </el-radio>
                                                </el-radio-group>

                                                <template #footer>
                                                    <div class="dialog-footer" style="display: flex; justify-content: space-between;">
                                                        <div style="display: flex; align-items: center; justify-content: flex-start;">
                                                            <img src="../../public/img/resources/money.png" style="height: 20px; width: 20px;">
                                                            <span style="margin-left: 5px;">菜品{{ amountSelect }}元</span>
                                                            &ensp;
                                                            <img src="../../public/img/resources/money.png" style="height: 20px; width: 20px;">
                                                            <span style="margin-left: 5px;">配送{{ deliverFee }}元</span>
                                                            &ensp;
                                                            <img src="../../public/img/resources/money.png" style="height: 20px; width: 20px;">
                                                            <span style="margin-left: 5px;">共{{ amountCart }}元</span>
                                                        </div>
                                                        <div style="display: flex; align-items: center; justify-content: flex-end;">
                                                            <el-button @click="outerVisible = false">取消</el-button>
                                                            <el-button @click="submitToDB">确认</el-button>
                                                        </div>
                                                    </div>
                                                </template>
                                            </el-dialog>
                                        </el-drawer>
                                    </el-menu-item>
                                </el-menu>
                            </el-col>
                        </el-row>
                    </el-aside>
                </div>
                <el-main>
                    <router-view></router-view>
                </el-main>
            </el-container>
        </el-container>
    </div>
</template>

<script setup>
    import { ref, onMounted, reactive, computed } from 'vue'
    import {
        computedOrder,
        deleteAllCart,
        deleteShoppingCart,
        getCategoryByMerchantId,
        getDish, getDishDetail,
        getMerchant, orderAdd,
        selectAllCart, updateShoppingCart,
    } from "../api/merchant";
    import {
        Document, Menu as IconMenu, Location, Setting,
        Bowl, ShoppingCartFull, Tickets, ArrowLeft, HomeFilled, OfficeBuilding, User, Iphone, Edit,
        Star, Delete, ShoppingCart
    } from '@element-plus/icons-vue'
    import { useRouter } from 'vue-router'
    import store from "../store";
    import MerchantMenu from '@/components/merchant/MerchantMenu.vue'
    import state from "../store";
    import { ElLoading, ElMessage } from "element-plus";
    import Decimal from 'decimal.js';
    import { addToCollectDish, addToCollectShop, deleteFromCollectShop, queryCollect } from "../api/Collect";
    import { getAddress } from "../api/addressSelect";
    import { confirmPay } from "../api/user";


    import { onBeforeUnmount } from "vue";
    import {$get} from "../utils/addressRequest";
    import AMapLoader from "@amap/amap-jsapi-loader";

    const newOrder = ref({})
    //向后端提交订单
    const submitToDB = () => {
        let list = []
        for (let i = 0; i < multipleSelection.value.length; i++) {
            list.push(multipleSelection.value[i].cartId)
        }
        if (list.length == 0) {
            ElMessage({
                message: '订单不能为空！',
                type: 'error',
            })
            return
        }
        const orderMap = {
            //订单信息
            order: {
                userId: userId.value,
                merchantId: merchantId.value,
                addressBookId: addId.value,
                payMethod: payMethod.value,
                notes: note.value,
                amount: amountCart.value,
                deliveryFee: deliverFee.value
            },
            //订单涉及的购物车信息
            list
        }
        orderAdd(orderMap).then(res => {
            if (res.data === false) {
                ElMessage({
                    message: '库存不足！',
                    type: 'error',
                })
                return
            }
            console.log(multipleSelection.value);
            console.log("res_id: " + res.data);
            //进入支付页面
            confirmPay({orderId: res.data}).then((ans) => {
                //调用支付宝统一收单下单并支付页面接口
                //将支付宝返回的表单字符串写在浏览器中，表单会自动触发submit提交
                // console.log(ans.data.data);
                document.write(ans.data.data);
            });
            newOrder.value = res.data
            console.log(newOrder.value)
            // handleSendButton()
        })
        ElMessage({
            message: '提交成功！',
            type: 'success',
        })
        outerVisible.value = false
        cart.value = false
    }



    const merchant = ref([])
    const category = ref([])



    const title = ref('返回')

    //是否显示购物车
    const cart = ref(false)

    //Foods存购物车查询到的菜品信息
    const Foods = ref([])
    //购物车表的数据
    const nowCart = ref([])

    //对象
    const food = ref({})
    const nowCart1 = []

    //收藏
    const showSc = ref(true)
    const router = useRouter()

    //金额
    const amount = ref(0)
    //选中菜品金额
    const amountSelect = ref(0)
    //加配送费
    const amountCart = ref(0)

    //当前选择的地址
    const addressNow = ref('')

    //按钮显示内容
    const buttonText = ref()

    //订单确认框
    const outerVisible = ref(false)
    const innerVisible = ref(false)

    //地址
    const addId = ref()
    const address = ref([])

    //备注
    const note = ref('')

    //配送费
    const deliverFee=ref(0)

    //改变地址
    const changeAddress = async (id,index) => {
        console.log(id)
        console.log(index)
        addId.value = id;
        addressNow.value = address.value[index].consignee + " " + address.value[index ].phone + " " + address.value[index ].provinceName + address.value[index ].cityName + address.value[index ].districtName + address.value[index ].detail
        //当前选择地址的信息
        let addressDetail=address.value[index].provinceName + address.value[index ].cityName + address.value[index ].districtName + address.value[index ].detail
        //计算经纬度
        let location= await computedLocation(addressDetail)
        //计算坐标距离
        let p1= new myAMap.LngLat(location.lng,location.lat)
        let p2= new myAMap.LngLat(lng.value,lat.value)
        let dis = myAMap.GeometryUtil.distance(p1,p2);
        distances.value=(dis / 1000).toFixed(2);
        computedDeliverFee(distances.value)
    }
    //距离
    const distances=ref(0)
    //店铺经纬度坐标
    const lng=ref()
    const lat=ref()

    //根据订单价格判断
    const checkOrderFee = ref(true)

    //计算根据距离计算配送费
    const computedDeliverFee=(distance)=>{
        if(distance<=parseFloat(3)){
            deliverFee.value=new Decimal(2)
        }else{
            deliverFee.value=new Decimal(2)
            let other = new Decimal((distance-3)/0.5)
            deliverFee.value=add(deliverFee.value,mul(other,0.2)).toFixed(2)
        }
        //更新总金额
        amountCart.value = add(deliverFee.value, amountSelect.value)
    }

    //支付方式
    const payMethod = ref()
    const methods = ref([
        { id: 0, name: '支付宝' },
        { id: 1, name: '微信' },
        { id: 2, name: '银行卡' },
    ])

    //将异步处理为同步
    const myInit = async () => {
        //同步执行，阻塞代码，直到获取结果位置
        const { data } = await getMerchant({ merchantId: merchantId.value })
        merchant.value.push(data)
        //根据商家id查找该商家有什么菜系
        //二级分类的菜系
        getCategoryByMerchantId({ id: data.id }).then(res2 => {
            for (let i = 0; i < res2.data.length; i++) {
                category.value.push(res2.data[i])
            }
        })
        //初始化收藏
        queryCollect({ userId: userId.value, merchantId: merchantId.value }).then(res => {
            if (res.data >= 1) {
                showSc.value = false;
            } else {
                showSc.value = true
            }
        })
    }

    //计算经纬度信息
    const computedLocation= async (Address)=>{
        let {geocodes} = await $get('https://restapi.amap.com/v3/geocode/geo?parameters',{
            //Web端的key
            key:'2b71974950a51f8c24eb45a1e462a84e',
            //地址
            address:Address
        })
        //坐标地址
        let location1=geocodes[0].location
        //分割为经纬度坐标
        const location11 = location1.split(",").map(parseFloat);
        let p1= new myAMap.LngLat(location11[0],location11[1])
        return p1
    }

    //地图计算配送费
    let myAMap;

    //初始化页面数据
    onMounted(async () => {
        const res =await AMapLoader.load({
            key: "0660b1d1e3b8275101d54732f4607219",             // 申请好的Web端开发者Key，首次调用 load 时必填
            version: "2.0",      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
            plugins: ['AMap.Geolocation','AMap.Geocoder'],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        })
        myAMap=res;
        myInit()
        openHot()
        let location=await computedLocation(merchantAddress.value)
        console.log(location)
        lng.value=location.lng
        lat.value=location.lat
        //webSocketInit()
    })

    //获取用户id
    const userId = computed(() => {
        return store.getters.getId
    })
    //获取商家id
    const merchantId = computed(() => {
        return store.getters.getMerchantId
    })
    //获取商家地址id
    const merchantAddress = computed(() => {
        return store.getters.getAddress
    })
    //跳转至菜单
    const btnToMenu = (id) => {
        const params = reactive({ id: id })
        router.push({ name: 'merchantmenu', params })
    }

    //初始化Foods
    const InitFoods = async (re) => {
        let myFoods = []
        let res = re.data
        for (let i = 0; i < res.length; i++) {
            // nowCart.value[i].id=res[i].id
            nowCart1.push(res[i])
            nowCart.value = nowCart1
            food.value = {}
            await getDishDetail({ id: res[i].dishId }).then(res2 => {
                food.value = res2.data
                food.value.cartId = res[i].id
                food.value.number = res[i].number
                myFoods.push(food.value)
            })
        }
        return myFoods
    }

    const InitCart = async () => {
        buttonText.value = "还差" + merchant.value[0].dropOffFee + "元即可下单"
        //同步执行，阻塞代码，直到获取结果位置
        nowCart.value = []
        Foods.value = []
        //获取数据
        const data = { userId: userId.value, merchantId: merchantId.value }
        //查询购物车
        const res = await selectAllCart(data)
        Foods.value = await InitFoods(res)
        nowCart.value = nowCart1
        computedSelect()
        computedAll()
        cart.value = true

    }

    //打开购物车
    const openCart = () => {

        InitCart()
    }

    const handleOpen = () => {
    }
    const handleClose = () => {
    }

    //店家添加到收藏文件夹
    const addSc = () => {
        //转换
        showSc.value = false;
        let userId = state.getters.getId
        let merchantId = state.getters.getMerchantId
        const data = { userId: userId, merchantId: merchantId }
        addToCollectShop(data).then(res => {
            ElMessage({
                message: '收藏店铺成功！',
                type: 'success',
            })
        })
    }
    //店家踢出收藏文件夹
    const deleteSc = () => {
        //转换
        showSc.value = true;
        let userId = state.getters.getId
        let merchantId = state.getters.getMerchantId
        const data = { userId, merchantId }
        deleteFromCollectShop(data).then(res => {
            ElMessage({
                message: '店铺已从收藏中移除！',
                type: 'success',
            })
        })
    }

    //清空购物车
    const toZero = () => {
        const data = { userId: userId.value, merchantId: merchantId.value }
        deleteAllCart(data).then(res => {
            Foods.value = []
            amount.value = 0
        })
        buttonText.value = "还差" + merchant.value[0].dropOffFee + "元即可下单"
        checkOrderFee.value = true
    }
    //跳转到商家主页
    const toIndex = () => {
        //params里的参数形式{key:value}
        router.push({ path: '/merchanthome/merchantindex' })
    }

    //改变购物车菜品数量
    //产品数量和购物车id
    const changeOrder = (number, id) => {
        let num = -1;
        nowCart.value.forEach(food => {
            num++;
            if (food.id == id) {
                let increment = number - food.number
                const cart = { id, increment };
                updateShoppingCart(cart)
                food.number = number
                if (number == 1 && increment == -1) {
                    ElMessage({
                        message: '最少购买一件！',
                        type: 'error',
                    })
                }
            }
        })
        computedSelect()
        computedAll()

    }

    //已选框列表
    const multipleTableRef = ref(null)
    const multipleSelection = ref([])

    //decimal：两数相加
    const add = (x, y) => {
        if (!x) {
            x = 0
        }
        if (!y) {
            y = 0
        }
        const xx = new Decimal(x)
        const yy = new Decimal(y)
        return xx.plus(yy).toNumber()
    }
    //decimal：两数相减
    const reduce = (x, y) => {
        if (!x) {
            x = 0
        }
        if (!y) {
            y = 0
        }
        const xx = new Decimal(x)
        const yy = new Decimal(y)
        return xx.minus(yy).toNumber()
    }
    //decimal：两数相乘
    const mul = (x, y) => {
        if (!x) {
            x = 0
        }
        if (!y) {
            y = 0
        }
        const xx = new Decimal(x)
        const yy = new Decimal(y)
        return xx.mul(yy).toNumber()
    }

    //计算勾选的值
    const computedSelect = async () => {
        amountSelect.value = 0
        await multipleSelection.value.forEach(food => {
            let amount1 = mul(food["number"], food["price"])
            amountSelect.value = add(amount1, amountSelect.value)
        })
        if (amountSelect.value >= merchant.value[0].dropOffFee) {
            checkOrderFee.value = false
            buttonText.value = "购买当前已选菜品"
        } else {
            checkOrderFee.value = true
            buttonText.value = "还差" + new Decimal(reduce(merchant.value[0].dropOffFee, amountSelect.value)) + "元即可下单"
        }


    }

    //计算整个购物车的值
    const computedAll = () => {
        amount.value = 0
        //food是对象
        const amount1 = new Decimal(0)
        Foods.value.forEach(foods => {
            let amount1 = mul(foods["number"], foods["price"])
            amount.value = add(amount1, amount.value)
        })
    }

    //勾选改变时触发
    const handleSelectionChange = (val) => {
        multipleSelection.value = val
        computedSelect()
    }

    //移除某一订单
    const deleteOrder = (id) => {
        let nowIndex = -1
        //移除时删除整个对象
        Foods.value.forEach(food => {
            nowIndex++
            if (food["id"] == id) {
                deleteShoppingCart({ id: food["cartId"] })
                amount.value -= food["price"] * food["number"]
                Foods.value.splice(nowIndex, 1)
            }
        })
        computedSelect()
        computedAll()
        ElMessage({
            message: '移除菜品成功！',
            type: 'success',
        })
    }

    //单个删除
    const deleteIt = (id) => {
        deleteOrder(id)
    }

    //添加到收藏列表，未做
    const toLike = (id) => {
        //保存到收藏的菜品中
        let userId = state.getters.getId
        let merchantId = state.getters.getMerchantId
        //用户id，商家id，菜品id
        const data = { userId, dishId: id }
        addToCollectDish(data).then(res => {
            ElMessage({
                message: '菜品收藏成功！',
                type: 'success',
            })
        })
    }

    //删除所有已选
    const deleteSelect = () => {
        multipleSelection.value.forEach(food => {
            deleteOrder(food["id"])
        })
    }
    //提交订单页面
    const btnSubmit = () => {
        amountCart.value = add(deliverFee.value, amountSelect.value)
        outerVisible.value = true
        address.value = []
        getAddress({ id: userId.value }).then(res => {
            for (let i = 0; i < res.data.length; i++) {
                address.value.push(res.data[i])
                address.value[i].index=i;
            }
        })
        console.log(address.value)
    }


    const openHot = () => {
        router.push({ path: '/merchanthome/merchantrecommend' })
    }

    //返回主页
    const toHome = () => {
        router.push({ path: '/home' })
    }

</script>
<style scoped>
    .bground {
        width: 100%;
      height: auto;
        background-color: rgba(0, 150, 150, 0.1);
        border: 1px solid #ccc;
        border-radius: 10px;
        background-attachment: fixed;
    }

    .cell-item {
        display: flex;
        align-items: center;
    }

    .margin-top {
        margin-top: 20px;
    }

    .menu-item-group {
        font-family: 楷体, Arial, sans-serif;
        font-size: 40px;
        font-weight: bold;
        background-color: rgb(176, 224, 230, 0.2);
    }

    .menu-item-group .el-menu-item-group _title {
        font-size: 36px;
        font-weight: bold;
    }

    .radio-item {
        display: flex;
        align-items: center;
    }

    .radio-content {
        display: flex;
        align-items: center;
    }

    .avatar {
        margin-right: 5px;
    }

    .radio-text {
        font-family: 楷体, Arial, sans-serif;
        font-size: 16px;
        font-weight: bold;
    }

    .custom-title {
        display: flex;
        align-items: center;
        font-size: 28px;
        font-weight: bold;
        color: #333;
    }

    .custom-title i {
        margin-right: 10px;
    }

    .custom-title span {
        font-size: 16px;
    }

    .custom-span {
        display: flex;
        align-items: center;
        font-size: 30px;
    }

    .custom-title {
        display: flex;
        align-items: center;
        justify-content: flex-start;
        font-size: 30px;
    }

    .title-style {
        font-size: 20px;
        font-weight: bold;

    }
</style>
